package org.ruiyichen.guizhou.agr.utils;

import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/8/25.
 */

public class ClassUtils<T> {

    /**
     * 使用reflect进行转换
     */
    public T mapToObject(Map<String, Object> map, Type type) {
        if (map == null)
            return null;
        T obj = null;
        try {
            obj = (T) type.getClass().newInstance();

            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }

                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
            }
        } catch (Exception e) {
            L.e(e.getMessage());
        }
        return obj;
    }

    public Map<String, Object> objectToMap(T obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            try {
                if (null == field.get(obj)) {
                    continue;
                }
                map.put(field.getName(), field.get(obj));
            } catch (Exception e) {
                L.e(e.getMessage());
            }
        }
        return map;
    }

    public List<T> mapListToObjectList(List<Map<String, Object>> mapList) {
        if (mapList == null)
            return null;
        List<T> list = new ArrayList<>();
        for (int i = 0; i < mapList.size(); i++) {
            list.add(mapToObject(mapList.get(i), new TypeToken<T>() {
            }.getType()));
        }
        return list;
    }

    public List<Map<String, Object>> objListToMapList(List<T> objList) {
        if (objList == null)
            return null;
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < objList.size(); i++) {
            list.add(objectToMap(objList.get(i)));
        }
        return list;
    }

}
